package tresp.bthreads;

import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;

import robocode.HitByBulletEvent;
import tresp.coordinator.ICoordinator;
import tresp.utils.BThreadVote;
import tresp.utils.ITankInfo;
import tresp.utils.logging.MyLogger;

/**
 * <b>StayAlive</b>
 * 
 * 
 * @author <font color="blue">Maxim Kirilov</font>
 *
 */
public class StayAlive extends BThread {

    private static Logger logger = MyLogger.getLogger( StayAlive.class );
    
    private AtomicReference<HitByBulletEvent> lastHitByBulletEvent;
    
    private ITankInfo tankInfo;
    
    public StayAlive(ICoordinator<BThreadVote> coordinator) {
	super(coordinator);
	logger.info("Stay Alive B-Thread created successfully");
	this.weight = 20D;
	
	tankInfo = coordinator.getTankInfo();
	lastHitByBulletEvent = new AtomicReference<HitByBulletEvent>();
    }


    @Override
    public void vote() {

	if ( tankInfo.getEnergy() < 40){
	    
	    coordinator.vote( createBThreadVote(BThreadType.FACTORIZED_MOVE, weight, 10D) );
	    coordinator.vote( createBThreadVote(BThreadType.PATTERN_MATCHER_TARGETING, weight, -5D) );
	}
	
	if ( lastHitByBulletEvent.getAndSet( null ) != null ){
	    coordinator.vote( createBThreadVote(BThreadType.FACTORIZED_MOVE, weight, 10D) );
	}
	
    }

    
    @Override
    public void onHitByBullet(HitByBulletEvent event){
	super.onHitByBullet(event);
	lastHitByBulletEvent.set( event );
    }
    

    @Override
    public String getName() {
	return "Stay Alive";
    }

}
